package com.chen10.cattle.service.impl;

import com.chen10.cattle.common.constants.WsEventConstants;
import com.chen10.cattle.common.enums.response.ErrorEnum;
import com.chen10.cattle.common.enums.friend.FriendRequestStatusEnums;
import com.chen10.cattle.common.enums.friend.FriendshipStatusEnums;
import com.chen10.cattle.common.enums.response.ResponseCodeEnum;
import com.chen10.cattle.common.exception.BusinessException;
import com.chen10.cattle.mapper.FriendRequestMapper;
import com.chen10.cattle.mapper.FriendshipMapper;
import com.chen10.cattle.model.dto.HandleFriendRequestDTO;
import com.chen10.cattle.model.dto.SendFriendRequestDTO;
import com.chen10.cattle.model.vo.FriendRequestListVO;
import com.chen10.cattle.service.FriendRequestService;
import com.chen10.cattle.ws.WebSocketHandler;
import com.chen10.cattle.ws.pojo.WsMessage;
import com.chen10.cattle.model.pojo.FriendRequests;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FriendRequestServiceImpl implements FriendRequestService {
    @Resource
    private FriendRequestMapper friendRequestMapper;
    @Resource
    private FriendshipMapper friendshipMapper;
    @Resource
    private WebSocketHandler webSocketHandler;
    /**
     * 获取好友请求列表
     * @param userId
     * @return
     */
    @Override
    public List<FriendRequestListVO> getFriendRequestList(Integer userId) {
        if(userId==null){
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        List<FriendRequestListVO> requestList = friendRequestMapper.getFriendRequestList(userId);
        return requestList;
    }


    /**
     *
     * @param handleFriendRequestDTO
     * @return 错误状态码
     */
    @Override
    @Transactional
    public int handleFriendRequest(HandleFriendRequestDTO handleFriendRequestDTO) {
        //校验参数
        if (handleFriendRequestDTO == null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }

        //检查参数
        Integer requestId = handleFriendRequestDTO.getRequestId();
        String status = handleFriendRequestDTO.getStatus();
        if (requestId == null || StringUtils.isEmpty(status)) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }

        FriendRequests friendRequests = friendRequestMapper.getByRequestId(requestId);
        Integer senderId = friendRequests.getSenderId();
        Integer receiverId  = friendRequests.getReceiverId();

        //判断是否已经是好友
        if (friendshipMapper.checkIsFriend(senderId, receiverId)) {
            friendRequestMapper.updateStatus(requestId,status);
            return ErrorEnum.ALREADY_FRIEND.getCode();
        }

        //如果是接受好友请求
        if (FriendRequestStatusEnums.ACCEPTED.getStatus().equals(status)) {
            //插入或更新好友关系表（二人之前可能加过好友，现在不是，再次同意）
            friendshipMapper.insertOrUpdate(senderId, receiverId, FriendshipStatusEnums.NORMAL.getStatus());
            // //更新好友请求表
        }

        friendRequestMapper.updateStatus(requestId,status);

        return ResponseCodeEnum.REQUEST_SUCCESS.getCode();
    }

    /**
     * 发送好友请求
     *
     * @param requestDTO
     */
    @Override
    public void sendFriendRequest(SendFriendRequestDTO requestDTO) {
        //校验参数
        if (requestDTO == null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }
        Integer senderId = requestDTO.getSenderId();
        Integer receiverId = requestDTO.getReceiverId();
        if (senderId == null || receiverId == null) {
            throw new BusinessException(ErrorEnum.PARAM_ERROR);
        }

        //判断是否已经是好友了
        if (friendshipMapper.checkIsFriend(senderId, receiverId)) {
            throw new BusinessException(ErrorEnum.ALREADY_FRIEND);
        }

        //查询好友请求表，检查是否存在状态为未处理的请求
        if (friendRequestMapper.getBySenderIdAndReceiverIdAndStatus(senderId, receiverId, FriendRequestStatusEnums.UNPROCESSED.getStatus()) != null) {
            throw new BusinessException(ErrorEnum.EXIST_UNPROCESSED_REQUEST);
        }

        //插入好友请求表
        FriendRequests request = new FriendRequests();
        request.setSenderId(senderId);
        request.setReceiverId(receiverId);
        request.setStatus(FriendRequestStatusEnums.UNPROCESSED.getStatus());
        request.setCreatedTime(new Date());

        friendRequestMapper.insert(request);


        //发送WebSocket消息给请求接收方
        WsMessage wsMessage = new WsMessage<>();
        wsMessage.setEvent(WsEventConstants.FRIEND_REQUEST_EVENT);
        wsMessage.setTimestamp(System.currentTimeMillis());
        webSocketHandler.sendMessageToUser(receiverId,wsMessage);
    }

}




